﻿using Microsoft.Ajax.Utilities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Helpers;
using System.Web.Mvc;
using System.Data.Entity;
using QBWeb.Models.QuestionFolder;
using QBWeb.Models.TestFolder;

namespace QBWeb.Models
{
    public class SetSqlTools
    {
        private readonly QBDbContext db = new QBDbContext();

        /// <summary>
        /// 设置题目表
        /// </summary>
        /// <param name="questName"></param>
        /// <param name="smallKnowModuleTbId"></param>
        /// <param name="questTypeTbId"></param>
        /// <param name="questAnalysis"></param>
        /// <param name="questLevel"></param>
        /// <param name="teacherId"></param>
        /// <param name="keyWords"></param>
        /// <returns></returns>
        public QuestionTb SetQuestionTb(string questName, int? smallKnowModuleTbId, int questTypeTbId, string questAnalysis, int questLevel,string teacherId,string keyWords)
        {
          
            
            var question = new QuestionTb
            {
                QuestName = questName,
                SmallKnowModuleTbId = smallKnowModuleTbId,
                QuestTypeTbId = questTypeTbId,
                QuestAnalysis = questAnalysis,
                QuestLevel = questLevel,
                CreateTime = DateTime.Now,
                TeacherId = teacherId,
                Keywords =keyWords ,
            };
            return question;
        }

        public QuestionTb SetQuestionTb(int questionId,string questName,int smallKnowModuleTBId,int questTypeTbId, string questAnalysis,int questLevel)
        {
            var question = new QuestionTb
            {
                Id=questionId,
                QuestName = questName,
                SmallKnowModuleTbId = smallKnowModuleTBId,
                QuestTypeTbId = questTypeTbId,
                QuestAnalysis = questAnalysis,
                QuestLevel = questLevel,
                CreateTime = DateTime.Now
            };
            return question;
        }

        /// <summary>
        /// 修改题目信息
        /// </summary>
        /// <param name="question"></param>
        /// <param name="questName"></param>
        /// <param name="questTypeTbId"></param>
        /// <param name="questAnalysis"></param>
        /// <param name="questLevel"></param>
        /// <returns></returns>
        public QuestionTb SetQuestionTb(QuestionTb question,string questName, int questTypeTbId, string questAnalysis, int questLevel)
        {
            question.QuestName = questName;
            question.QuestTypeTbId = questTypeTbId;
            question.QuestAnalysis = questAnalysis;
            question.QuestLevel = questLevel;
            question.ModifyTime = DateTime.Now;
            return question;
        }
        /// <summary>
        /// 设置单选题表
        /// </summary>
        /// <param name="options"></param>
        /// <param name="choiceValue"></param>
        /// <param name="choiceChecked"></param>
        /// <returns></returns>
        public SingleChoiceTb SetSingleChoiceTb(string[] options, string[] choiceValue, string[] choiceChecked)
        {
            var value = string.Join(";", choiceValue);
            var option = string.Join(";", options);
            var correctOption = string.Join(";", choiceChecked);
            var singleChoice = new SingleChoiceTb
            {
                Options = option,
                Value = value,
                CorrectOption =correctOption
            };
            return singleChoice;
        }

        public List<SingleChoiceTb> SetSingleChoiceTb(int questId, string[] options, string[] values,string[] correctOptions,int questTypeTbId)
        {
            //string[] option = options.Split(new char[] { ',' });
            //string[] value = values.Split(new char[] { ',' });
            //string[] correctOption = correctOptions.Split(new char[] { ',' });
            List<SingleChoiceTb> singleChoiceTbs = new List<SingleChoiceTb>();
            for(int i=0; i<options.Length; i++)
            {
                var singleChoiceTb = new SingleChoiceTb()
                {
                    QuestionTbId = questId,
                    Options = options[i],
                    Value = values[i],
                    CorrectOption =correctOptions[i],
                    QuestTypeTbId = questTypeTbId
                };
                singleChoiceTbs.Add(singleChoiceTb);
            }
            return singleChoiceTbs;
        }

        public TrueFalseTb SetTrueFalseTb(int correctValue)
        {
            var trueFalseTb = new TrueFalseTb
            {
                CorrectValue = correctValue,
            };
            return trueFalseTb;
        }

        public TrueFalseTb SetTrueFalseTb(int questionTbId,int correctValue,int questTypeTbId)
        {
            var trueFalseTb = new TrueFalseTb()
            {
                QuestionTbId = questionTbId,
                CorrectValue = correctValue,
                QuestTypeTbId = questTypeTbId
            };
            return trueFalseTb;
        }

        /// <summary>
        /// 更新判断题数据
        /// </summary>
        /// <param name="trueFalse"></param>
        /// <param name="correctValue"></param>
        /// <returns></returns>
        public TrueFalseTb UpdateTrueFalseTb(TrueFalseTb trueFalse,int correctValue)
        {
            trueFalse.CorrectValue = correctValue;
            return trueFalse;
        }

        public BlanksTb SetBlanksTb(string correctValue)
        {
            var blanksTb = new BlanksTb
            {
                CorrectValue = correctValue
            };
            return blanksTb;
        }

        public BlanksTb SetBlanksTb(int questionTbId,string correctValue,int questTypeTbId)
        {
            var blanksTb = new BlanksTb
            {
                QuestionTbId = questionTbId,
                CorrectValue = correctValue,
                QuestTypeTbId = questTypeTbId
            };
            return blanksTb;
        }

        public BlanksTb UpdateBlanksTb(BlanksTb blanks,string correctValue)
        {
            blanks.CorrectValue = correctValue;
            return blanks;
        }

        public TestPaperTb SetTestPaperTb(string testName, string creator,int issueId,int cid)
        {
            var testPaperTb = new TestPaperTb
            {
                TestName = testName,
                Creator = creator,  //获取当前用户的登录名称，没有时为空
                CreateTime = DateTime.Now,
                IssueId = issueId,
                CurriculaId = cid
            };
            return testPaperTb;
        }

        public TestPaperTb SetTestPaperTb(string testName,string creator,DateTime modifyTime)
        {
            var testPaperTb = new TestPaperTb
            {
                TestName = testName,
                Creator = creator,  //获取当前用户的登录名称，没有时为空
                ModifyTime = modifyTime
            };
            return testPaperTb;
        }

        public Issue SetIssue(int status)
        {
            var issue = new Issue
            { 
                Status = status
            };
            return issue;
        }
        public Issue SetIssue(Issue issue,string testNotes,DateTime startTime,DateTime endTime,int onTime,int status)
        {
            issue.TestNotes = testNotes;
            issue.StartTime = startTime;
            issue.EndTime = endTime;
            issue.OnTime = onTime;
            issue.Status = status;
            return issue;
        }
        /// <summary>
        ///学生获取题目数据
        /// </summary>
        /// <param name="testPaperTbId"></param>
        /// <returns></returns>
        public List<object> GetDataByStu(int? testPaperTbId)
        {
            var testDetails = db.TestDetails.Where(t => t.TestPaperTbId == testPaperTbId).ToList();//试卷题目信息表
            var questIds = new List<int>();//题目Id集合
            var questScore = new List<int>();//题目分数集合
            foreach (var t in testDetails)
            {
                questIds.Add(t.QuestId);
                questScore.Add(t.Score);
            }

            var data = new List<object>();  //题目数据集合
            for (var i = 0; i < questIds.Count; i++)
            {
                var questionTb = db.QuestionTbs.Find(Convert.ToInt32(questIds[i]));
                if (questionTb.QuestTypeTbId == 1)
                {
                    var questionTbs = db.SingleChoiceTbs.Where(t => t.QuestionTbId == questionTb.Id).Include(t => t.QuestionTb).First();
                    var questionValue = db.SingleChoiceTbs.Where(t => t.QuestionTbId == questionTb.Id);

                    string strValue = "";//选择题的选项
                    string strAnswer = "";//选择题答案
                    foreach (var x in questionValue)
                    {
                        strValue += x.Value + "::";
                        //if (x.CorrectOption == "1")
                        //{
                        //    strAnswer = x.Options;
                        //}
                    }
                    data.Add(new
                    {
                        QuestionIndex = i,
                        QuestionType = questionTbs.QuestTypeTbId,
                        QuestionId = questionTbs.QuestionTbId,
                        QuestionTitle = questionTbs.QuestionTb.QuestName,
                        QuestionItems = strValue,
                        QuestionAnswer = strAnswer,
                        QuestionAnalysis = questionTb.QuestAnalysis,
                        QuestionScore = questScore[i],
                        QuestionLevel = questionTb.QuestLevel,
                        QuestKeyWords = questionTb.Keywords
                    });
                }
                else if (questionTb.QuestTypeTbId == 2)
                {
                    var questionTbs = db.TrueFalseTbs.Where(t => t.QuestionTbId == questionTb.Id).Include(t => t.QuestionTb).First();
                    data.Add(new
                    {
                        QuestionIndex = i,
                        QuestionType = questionTbs.QuestTypeTbId,
                        QuestionId = questionTbs.QuestionTbId,
                        QuestionTitle = questionTbs.QuestionTb.QuestName,
                        QuestionItems = "",
                        QuestionAnswer = questionTbs.CorrectValue.ToString(),
                        QuestionAnalysis = questionTb.QuestAnalysis,
                        QuestionScore = questScore[i],
                        QuestionLevel = questionTb.QuestLevel,
                        QuestKeyWords = questionTb.Keywords
                    });
                }
                else if (questionTb.QuestTypeTbId == 3)
                {
                    var questionTbs = db.BlanksTbs.Where(t => t.QuestionTbId == questionTb.Id).Include(t => t.QuestionTb).First();
                    data.Add(new
                    {
                        QuestionIndex = i,
                        QuestionType = questionTbs.QuestTypeTbId,
                        QuestionId = questionTbs.QuestionTbId,
                        QuestionTitle = questionTbs.QuestionTb.QuestName,
                        QuestionItems = "",
                        QuestionAnswer = questionTbs.CorrectValue.ToString(),
                        QuestionAnalysis = questionTb.QuestAnalysis,
                        QuestionScore = questScore[i],
                        QuestionLevel = questionTb.QuestLevel,
                        QuestKeyWords = questionTb.Keywords
                    });
                }
                else { }
            }
            return data;
        }


        /// <summary>
        /// 获取题目数据
        /// </summary>
        /// <param name="testPaperTbId"></param>
        /// <returns>List<object />
        /// </returns>
        public List<object> GetDbQuestionByTestId(int testPaperTbId)
        {
            //var testDetails = db.TestDetails.Where(t => t.TestPaperTbId == testPaperTbId).ToList();//试卷题目信息表
            object[] param = { testPaperTbId };
            const string sql = "select * from TestDetailsTbs where TestPaperTbId =@P0 order by QuestIndex";
            var testDetails = db.Database.SqlQuery<TestDetailsTb>(sql, param).ToList();
            var questIds = new List<int>();//题目Id集合
            var questScore = new List<int>();//题目分数集合
            foreach (var t in testDetails)
            {
                questIds.Add(t.QuestId);
                questScore.Add(t.Score);
            }

            var data = new List<object>();  //题目数据集合
            for (var i = 0; i < questIds.Count; i++)
            {
                var questionTb = db.QuestionTbs.Find(Convert.ToInt32(questIds[i]));
                if (questionTb.QuestTypeTbId == 1)
                {
                    var questionTbs = db.SingleChoiceTbs.Where(t => t.QuestionTbId == questionTb.Id).Include(t => t.QuestionTb).First();
                    var questionValue = db.SingleChoiceTbs.Where(t => t.QuestionTbId == questionTb.Id);

                    string strValue = "";//选择题的选项
                    string strAnswer = "";//选择题答案
                    foreach (var x in questionValue)
                    {
                        strValue += x.Value + "::";
                        if (x.CorrectOption == "1")
                        {
                            strAnswer = x.Options;
                        }
                    }
                    data.Add(new
                    {
                        QuestionIndex = i,
                        QuestionType = questionTbs.QuestTypeTbId,
                        QuestionId = questionTbs.QuestionTbId,
                        QuestionTitle = questionTbs.QuestionTb.QuestName,
                        QuestionItems = strValue,
                        QuestionAnswer = strAnswer,
                        QuestionAnalysis = questionTb.QuestAnalysis,
                        QuestionScore = questScore[i],
                        QuestionLevel = questionTb.QuestLevel,
                        QuestKeyWords =questionTb.Keywords
                    });
                }
                else if (questionTb.QuestTypeTbId == 2)
                {
                    var questionTbs = db.TrueFalseTbs.Where(t => t.QuestionTbId == questionTb.Id).Include(t => t.QuestionTb).First();
                    data.Add(new
                    {
                        QuestionIndex = i,
                        QuestionType = questionTbs.QuestTypeTbId,
                        QuestionId = questionTbs.QuestionTbId,
                        QuestionTitle = questionTbs.QuestionTb.QuestName,
                        QuestionItems = "",
                        QuestionAnswer = questionTbs.CorrectValue.ToString(),
                        QuestionAnalysis = questionTb.QuestAnalysis,
                        QuestionScore = questScore[i],
                        QuestionLevel = questionTb.QuestLevel,
                        QuestKeyWords = questionTb.Keywords
                    });
                }
                else if (questionTb.QuestTypeTbId == 3)
                {
                    var questionTbs = db.BlanksTbs.Where(t => t.QuestionTbId == questionTb.Id).Include(t => t.QuestionTb).First();
                    data.Add(new
                    {
                        QuestionIndex = i,
                        QuestionType = questionTbs.QuestTypeTbId,
                        QuestionId = questionTbs.QuestionTbId,
                        QuestionTitle = questionTbs.QuestionTb.QuestName,
                        QuestionItems = "",
                        QuestionAnswer = questionTbs.CorrectValue.ToString(),
                        QuestionAnalysis = questionTb.QuestAnalysis,
                        QuestionScore = questScore[i],
                        QuestionLevel = questionTb.QuestLevel,
                        QuestKeyWords = questionTb.Keywords
                    });
                }
                else { }
            }
            return data;
        }

        public List<object> GetDbQuestionByQuestId(string questId)
        {
            
            string[] questIds = questId.Split(';');//题目Id集合

            var data = new List<Object>();  //题目数据集合
            for (int i = 0; i < questIds.Length; i++)
            {
                QuestionTb questionTb = db.QuestionTbs.Find(Convert.ToInt32(questIds[i]));
                if (questionTb.QuestTypeTbId == 1)
                {
                    var questionTbs = db.SingleChoiceTbs.Where(t => t.QuestionTbId == questionTb.Id).Include(t => t.QuestionTb).First();
                    var questionValue = db.SingleChoiceTbs.Where(t => t.QuestionTbId == questionTb.Id);

                    var strValue = "";//选择题的选项
                    var strAnswer = "";//选择题答案
                    foreach (var x in questionValue)
                    {
                        strValue += x.Value + "::";
                        if (x.CorrectOption == "1")
                        {
                            strAnswer = x.Options;
                        }
                    }
                    data.Add(new
                    {
                        QuestionType = questionTbs.QuestTypeTbId,
                        QuestionId = questionTbs.QuestionTbId,
                        QuestionTitle = questionTbs.QuestionTb.QuestName,
                        QuestionItems = strValue,
                        QuestionAnswer = strAnswer,
                        QuestionAnalysis = questionTbs.QuestionTb.QuestAnalysis,
                        QuestionLevel = questionTbs.QuestionTb.QuestLevel,
                        QuestKeyWords = questionTb.Keywords
                    });
                }
                else if (questionTb.QuestTypeTbId == 2)
                {
                    var questionTbs = db.TrueFalseTbs.Where(t => t.QuestionTbId == questionTb.Id).Include(t => t.QuestionTb).First();
                    data.Add(new
                    {
                        QuestionType = questionTbs.QuestTypeTbId,
                        QuestionId = questionTbs.QuestionTbId,
                        QuestionTitle = questionTbs.QuestionTb.QuestName,
                        QuestionItems = "",//判断题不需要选项
                        QuestionAnswer = questionTbs.CorrectValue.ToString(),
                        QuestionAnalysis = questionTbs.QuestionTb.QuestAnalysis,
                        QuestionLevel = questionTbs.QuestionTb.QuestLevel,
                        QuestKeyWords = questionTb.Keywords
                    });
                }
                else if (questionTb.QuestTypeTbId == 3)
                {
                    var questionTbs = db.BlanksTbs.Where(t => t.QuestionTbId == questionTb.Id).Include(t => t.QuestionTb).First();
                    data.Add(new
                    {
                        QuestionType = questionTbs.QuestTypeTbId,
                        QuestionId = questionTbs.QuestionTbId,
                        QuestionTitle = questionTbs.QuestionTb.QuestName,
                        QuestionItems = "",//填空题不需要选项
                        QuestionAnswer = questionTbs.CorrectValue.ToString(),
                        QuestionAnalysis = questionTbs.QuestionTb.QuestAnalysis,
                        QuestionLevel = questionTbs.QuestionTb.QuestLevel,
                        QuestKeyWords = questionTb.Keywords
                    });
                }
                else { }
            }
            return data;
        }

        public object GetQuestionById(int questionId)
        {
            object data = null;
            QuestionTb questionTb = db.QuestionTbs.Find(questionId);
            if (questionTb.QuestTypeTbId == 1)
            {
                var questionTbs = db.SingleChoiceTbs.Where(t => t.QuestionTbId == questionTb.Id).Include(t => t.QuestionTb).First();
                var questionValue = db.SingleChoiceTbs.Where(t => t.QuestionTbId == questionTb.Id);

                var strValue = "";//选择题的选项
                var strAnswer = "";//选择题答案
                foreach (var x in questionValue)
                {
                    strValue += x.Value + "::";
                    if (x.CorrectOption == "1")
                    {
                        strAnswer = x.Options;
                    }
                }
                data = new
                {
                    QuestionType = questionTbs.QuestTypeTbId,
                    QuestionId = questionTbs.QuestionTbId,
                    QuestionTitle = questionTbs.QuestionTb.QuestName,
                    QuestionItems = strValue,
                    QuestionAnswer = strAnswer,
                    QuestionAnalysis = questionTbs.QuestionTb.QuestAnalysis,
                    QuestionLevel = questionTbs.QuestionTb.QuestLevel,
                    QuestKeyWords = questionTb.Keywords
                };
            }
            else if (questionTb.QuestTypeTbId == 2)
            {
                var questionTbs = db.TrueFalseTbs.Where(t => t.QuestionTbId == questionTb.Id).Include(t => t.QuestionTb).First();
                data = new
                {
                    QuestionType = questionTbs.QuestTypeTbId,
                    QuestionId = questionTbs.QuestionTbId,
                    QuestionTitle = questionTbs.QuestionTb.QuestName,
                    QuestionItems = "",//判断题不需要选项
                    QuestionAnswer = questionTbs.CorrectValue.ToString(),
                    QuestionAnalysis = questionTbs.QuestionTb.QuestAnalysis,
                    QuestionLevel = questionTbs.QuestionTb.QuestLevel,
                    QuestKeyWords = questionTb.Keywords
                };
            }
            else if (questionTb.QuestTypeTbId == 3)
            {
                var questionTbs = db.BlanksTbs.Where(t => t.QuestionTbId == questionTb.Id).Include(t => t.QuestionTb).First();
                data = new
                {
                    QuestionType = questionTbs.QuestTypeTbId,
                    QuestionId = questionTbs.QuestionTbId,
                    QuestionTitle = questionTbs.QuestionTb.QuestName,
                    QuestionItems = "",//填空题不需要选项
                    QuestionAnswer = questionTbs.CorrectValue.ToString(),
                    QuestionAnalysis = questionTbs.QuestionTb.QuestAnalysis,
                    QuestionLevel = questionTbs.QuestionTb.QuestLevel,
                    QuestKeyWords = questionTb.Keywords
                };
            }
            else { }
            return data;
        }

        /// <summary>
        /// 获取word识别的结果 并格式化数据到前台
        /// </summary>
        /// <param name="resCache"></param>
        /// <returns></returns>
        public List<object> GetWordQuestionByCache(Dictionary<int, Dictionary<string, string>> resCache)
        {

            var data = new List<object>();  //题目数据集合
            var count = -1;
            foreach (var item in resCache)
            {
                switch (item.Value["type"])
                {
                    case "1":
                    {

                        var strValue = "";//选择题的选项
                        var strAnswer = "";//选择题答案
                        for (var k = 1; k <= item.Value.Count - 6; k++)
                        {
                            strValue += item.Value["option" + k] + "::";
                            strAnswer = item.Value["correct"];
                        }

                        data.Add(new
                        {
                            QuestionType = 1,
                            QuestionId = count,
                            QuestionTitle = item.Value["quest"],
                            QuestionItems = strValue,
                            QuestionScore=int.Parse(item.Value["score"]),
                            QuestionAnswer = strAnswer,
                            QuestionAnalysis =item.Value["analysis"],
                            QuestionLevel = 3,
                            QuestKeyWords=item.Value["keyWords"]
                        });
                        break;
                    }
                    case "2":
                    {
                        var correctVal = "";
                        switch (item.Value["correct"])
                        {
                                case "对":
                                    correctVal = "1";
                                    break;
                                case "错":
                                    correctVal = "0";
                                    break;
                            }
                        data.Add(new
                        {
                            QuestionType = 2,
                            QuestionId =count,
                            QuestionTitle = item.Value["quest"],
                            QuestionItems = "",//判断题不需要选项
                            QuestionScore = int.Parse(item.Value["score"]),
                            QuestionAnswer = correctVal,
                            QuestionAnalysis = "",
                            QuestionLevel =3,
                            QuestKeyWords = item.Value["keyWords"]
                        });
                        break;
                    }
                    case "3":
                    {
                        data.Add(new
                        {
                            QuestionType = 3,
                            QuestionId = count,
                            QuestionTitle = item.Value["quest"],
                            QuestionItems = "",//填空题不需要选项
                            QuestionScore = int.Parse(item.Value["score"]),
                            QuestionAnswer = item.Value["blanks"],
                            QuestionAnalysis = "",
                            QuestionLevel =3,
                            QuestKeyWords = item.Value["keyWords"]
                        });
                        break;
                    }
                }
                count--;
            }
            return data;
        }
    }
}